import logging
import colorlog
from app.config import settings

def setup_logger(name: str) -> logging.Logger:
    """
    设置并返回一个配置好的日志记录器
    """
    logger = logging.getLogger(name)
    log_level = getattr(logging, settings.LOG_LEVEL)
    logger.setLevel(log_level)

    # 创建控制台处理器
    if not logger.handlers:
        console_handler = colorlog.StreamHandler()
        # 定义不同日志级别对应的颜色
        log_colors = {
            'DEBUG': 'cyan',
            'INFO': 'green',
            'WARNING': 'yellow',
            'ERROR': 'red',
            'CRITICAL': 'bold_red',
        }
        formatter = colorlog.ColoredFormatter(
            '%(log_color)s%(asctime)s - %(name)s - %(levelname)s - %(message)s',
            log_colors=log_colors
        )
        console_handler.setFormatter(formatter)
        logger.addHandler(console_handler)

    return logger